package com.atguigu.orderservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.orderservice.entity.Order;
import com.atguigu.orderservice.entity.PayLog;
import com.atguigu.orderservice.mapper.PayLogMapper;
import com.atguigu.orderservice.service.OrderService;
import com.atguigu.orderservice.service.PayLogService;
import com.atguigu.orderservice.util.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;

import javafx.util.converter.LocalDateTimeStringConverter;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author haoyue1573
 * @since 2023-03-24
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

	@Resource
	private OrderService orderService;

	@Override
	public Map<String,String> createNative(String orderNo) {

		try {
			//根据订单id获取订单信息
			QueryWrapper<Order> wrapper = new QueryWrapper<>();
			wrapper.eq("order_no",orderNo);
			Order order = orderService.getOne(wrapper);
			Map<String,String> map = new HashMap<>();
			// todo 1、设置支付参数->也可以将这些values配置在配置资源中
			map.put("appid", "wx74862e0dfcf69954");
			map.put("mch_id", "1558950191");
			map.put("nonce_str", WXPayUtil.generateNonceStr());
			map.put("body", order.getCourseTitle());
			map.put("out_trade_no", orderNo);
			map.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
			map.put("spbill_create_ip", "127.0.0.1");
			map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
			map.put("trade_type", "NATIVE");

			//2、HTTPClient来根据URL访问第三方接口并且传递参数->查询是否支付成功
			HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

			//client设置参数
			client.setXmlParam(WXPayUtil.generateSignedXml(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
			client.setHttps(true);
			client.post();
			//3、返回第三方的数据
			String xml = client.getContent();
			Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
			//4、封装返回结果集

			Map<String,String> OrderMap = new HashMap<>();
			OrderMap.put("out_trade_no", orderNo);
			OrderMap.put("course_id", order.getCourseId());
			OrderMap.put("total_fee", order.getTotalFee().toString());
			OrderMap.put("result_code", resultMap.get("result_code"));
			OrderMap.put("code_url", resultMap.get("code_url"));

			//微信支付二维码2小时过期，可采取2小时未支付取消订单
			//redisTemplate.opsForValue().set(orderNo, map, 120, TimeUnit.MINUTES);
			return OrderMap;
		} catch (Exception e) {
			e.printStackTrace();
			return new HashMap<>();
		}

	}

	@Override
	public Map<String, String> queryPayStatus(String orderNo) {
		Map<String,String> map = new HashMap<>();
		// todo 1、设置支付参数->也可以将这些values配置在配置资源中
		map.put("appid", "wx74862e0dfcf69954");
		map.put("mch_id", "188101792820");
		map.put("out_trade_no", orderNo);
		map.put("nonce_str",WXPayUtil.generateNonceStr());

		HttpClient httpClient=new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");

		//client设置参数
		try {
			httpClient.setXmlParam(WXPayUtil.generateSignedXml(map, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
			httpClient.setHttps(true);
			httpClient.post();
			//3、返回第三方的数据
			String xml = httpClient.getContent();
	         return WXPayUtil.xmlToMap(xml) ;
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	 return new HashMap<>();
	}

	/**
	 * 添加支付记录,修改订单状态
	 * @param map
	 */
	public void updateOrderStatus(Map<String, String> map) {
		//获取订单id
		String orderNo = map.get("out_trade_no");
		//根据订单id查询订单信息
		QueryWrapper<Order> wrapper = new QueryWrapper<>();
		wrapper.eq("order_no",orderNo);
		Order order = orderService.getOne(wrapper);
		Integer status = order.getStatus();
		if(status == 1) return;
		order.setStatus(1);
		orderService.updateById(order);

		//记录支付日志
		PayLog payLog=new PayLog();
		payLog.setOrderNo(order.getOrderNo());//支付订单号
		payLog.setPayTime(LocalDateTime.now());
		payLog.setPayType(1);//支付类型
		payLog.setTotalFee(order.getTotalFee());//总金额(分)
		payLog.setTradeState(map.get("trade_state"));//支付状态
		payLog.setTransactionId(map.get("transaction_id"));
		payLog.setAttr(JSONObject.toJSONString(map));
		baseMapper.insert(payLog);//插入到支付日志表



	}
}
